<?php
/**
 * 商品类
 */
namespace app\admin\controller;
use app\admin\controller\Common;
class Goods extends Common{

	/**
	 * 展示商品列表页
	 */
	public function lst(){

		//分配模版标头信息变量
		$this->setPageTitle( "商品列表","添加商品",url('addShow') );

		//分页获取商品信息
		$field = 'gid,goods_name,static_url,market_price,shop_price,is_promote,is_on_sale,is_hot,is_new,is_best,pic_small,sort,a.account';
		$goods = db('goods as g')->field($field)->join('jd_admin a','g.aid = a.aid','LEFT')->order('gid desc')->where('is_delete','=',0)->paginate(config('paginate.list_rows'));

		//分配变量
		$this->assign('goods',$goods);
		
		return $this->fetch();
	}

	/**
	 * 展示商品添加页
	 */
	public function addShow(){

		//分配模版标头信息变量
		$this->setPageTitle( "添加商品","商品列表",url('lst') );

		//获取分类
		$cats = db('category')->field('cid,cat_name,parent_id')->select();
		$cats = getLevelTree( $cats, 'cid', 'parent_id', $pid=0,$level=0 );

		//获取品牌
		$brands = db('brand')->field('bid,brand_name')->select();

		//获取会员等级信息
		$members = db('member_level')->field('lid,level_name,rate')->select();

		//获取类型
		$types = db('type')->select();
		
		//分配变量
		$this->assign('cats',$cats);
		$this->assign('brands',$brands);
		$this->assign('members',$members);
		$this->assign('types',$types);

		return $this->fetch('add');
	}

	/**
	 * 添加商品
	 */
	public function add(){
		
		//安全处理 
		if( !request()->isPost() ){

			$this->error('您访问的页面不存在！');

		}
		
		//验证信息
		$validate = \think\Loader::validate('Goods');
		if( !$validate->check( input('post.') ) ){

			$this->error($validate->getError());

		}
		
		//处理商品名称样式
		$style = '';
		//加粗
		if( input('post.isStrong') ){
			$style = 'font-weight:700;';
		}

		//倾斜
		if( input('post.isItalic') ){

			$style .= 'font-style:italic;';
		}

		//描红
		if( input('post.isRed') ){
			$style .= 'color:red;';
		}
		 
		//收集商品表相关表单信息
		$data['goods_name'] = input('post.goodName');
		$data['goods_name_style'] = $style;
		$data['cid'] = input('post.cat_id')+0;
		$data['bid'] = input('post.brand_id')+0;
		$data['market_price'] = input('post.marketPrice');
		$data['shop_price'] = input('post.shopPrice');
		$data['is_promote'] = input('post.promote',0);
		$data['promote_price'] = input('post.promote_price',0);
		$data['promote_start_time'] = strtotime( input('post.start_time') ); 
		$data['promote_end_time'] = strtotime( input('post.end_time') );
		$data['jifen'] = input('post.jf');
		$data['jyz'] = input('post.jingyan');
		$data['jifen_price'] = input('post.jifenPrice');
		$data['pic_small'] = input('post.logo_small');
		$data['pic_medium'] = input('post.logo_medium');
		$data['pic_big'] = input('post.logo_big');
		$data['is_hot'] = input('post.isHot');
		$data['is_new'] = input('post.isNew');
		$data['is_best'] = input('post.isBest');
		$data['is_on_sale'] = input('post.isSale');
		$data['sku_unit'] = input('post.unit');
		$data['click'] = input('post.view');
		$data['sort'] = input('post.sort');
		$data['create_time'] = time();
		$data['update_time'] = time();
		$data['tid'] = input('post.type_id');
		$data['aid'] = session('id');
		
		//插入商品
		$goodsModel = new \app\admin\model\Goods();
		
		if( $goodsModel->allowField(true)->save( $data ) ){

			// 商品页静态化
			$gid = $goodsModel->getData('gid');
			$this->redirect('index/goods/goods', ['id' => $gid,'type'=>'add']);

		}else{

			$this->error( '添加失败！',url('lst') );

		}

	}

	/**
	 * 展示商品修改页
	 */
	public function editShow(){

		//分配模版标头信息变量
		$this->setPageTitle( "修改商品","商品列表",url('lst') );

		//获取分类
		$cats = db('category')->field('cid,cat_name,parent_id')->select();
		$cats = getLevelTree( $cats, 'cid', 'parent_id', $pid=0,$level=0 );

		//获取品牌
		$brands = db('brand')->field('bid,brand_name')->select();

		//获取会员等级信息
		$members = db('member_level')->field('lid,level_name,rate')->select();

		//获取类型
		$types = db('type')->select();

		//获取商品信息
		$id = input('id')+0;
		$good = db('goods as g')->join('jd_goods_info gi','g.gid = gi.gid','LEFT')->where('g.gid','=',$id)->find();

		//获取扩展分类id
		$extCats = db('goods_category')->where('gid','=',$id)->column('cid');

		//获取会员价格
		$memPrices = db('member_price')->where('gid','=',$id)->column('lid,member_price');

		//获取该商品所属类型下的所有属性
		$attrs = db('attrs')->field('aid,attr_name,input_type,attr_type,attr_value')->where('tid','=',$good['tid'])->select();


		
		//获取商品属性
		$data = db('goods_attrs')->field('aid,attr_value')->where('gid','=',$id)->select();
		$goodAttrs = [];
		foreach ($data as $k => $v) {

			$goodAttrs[$v['aid']][] = $v["attr_value"];

		}
		//q($goodAttrs);
		//获取商品相册
		$pics = db('pics')->field('pid,pic_big,pic_medium,pic_small,sort')->where('gid','=',$id)->order('sort')->select();
		
		
		//分配变量
		$this->assign('cats',$cats);
		$this->assign('brands',$brands);
		$this->assign('members',$members);
		$this->assign('types',$types);
		$this->assign('good',$good);
		$this->assign('extCats',$extCats);
		$this->assign('memPrices',$memPrices);
		$this->assign('attrs',$attrs);
		$this->assign('goodAttrs',$goodAttrs);
		$this->assign('pics',$pics);

		return $this->fetch('edit');
	}

	/**
	 * 修改商品
	 */
	public function edit(){
		
		//安全处理 
		if( !request()->isPost() ){

			$this->error('您访问的页面不存在！');

		}
		
		//验证信息
		$validate = \think\Loader::validate('Goods');
		if( !$validate->check( input('post.') ) ){

			$this->error($validate->getError());

		}
		
		//处理商品名称样式
		$style = '';
		//加粗
		if( input('post.isStrong') ){
			$style = 'font-weight:700;';
		}

		//倾斜
		if( input('post.isItalic') ){

			$style .= 'font-style:italic;';
		}

		//描红
		if( input('post.isRed') ){
			$style .= 'color:red;';
		}
		
		//收集商品表相关表单信息
		$data['goods_name'] = input('post.goodName');
		$data['goods_name_style'] = $style;
		$data['cid'] = input('post.cat_id')+0;
		$data['bid'] = input('post.brand_id')+0;
		$data['market_price'] = input('post.marketPrice');
		$data['shop_price'] = input('post.shopPrice');
		$data['is_promote'] = input('post.promote',0);
		$data['promote_price'] = input('post.promote_price',0);
		$data['promote_start_time'] = strtotime( input('post.start_time') ); 
		$data['promote_end_time'] = strtotime( input('post.end_time') );
		$data['jifen'] = input('post.jf');
		$data['jyz'] = input('post.jingyan');
		$data['jifen_price'] = input('post.jifenPrice');
		$data['pic_small'] = input('post.logo_small');
		$data['pic_medium'] = input('post.logo_medium');
		$data['pic_big'] = input('post.logo_big');
		$data['is_hot'] = input('post.isHot');
		$data['is_new'] = input('post.isNew');
		$data['is_best'] = input('post.isBest');
		$data['is_on_sale'] = input('post.isSale');
		$data['sku_unit'] = input('post.unit');
		$data['click'] = input('post.view');
		$data['sort'] = input('post.sort');
		$data['create_time'] = time();
		$data['update_time'] = time();
		$data['tid'] = input('post.type_id');
		$data['aid'] = session('id');
		$data['gid'] = input('post.id')+0;
		
		//插入商品
		$goodsModel = new \app\admin\model\Goods();
		
		if( $goodsModel->allowField(true)->isUpdate(true)->save( $data ) ){

			// 商品页静态化
			$this->redirect('index/goods/goods', ['id' => $data['gid'],'type'=>'edit']);

		}else{

			$this->error( '修改失败！',url('lst') );

		}

	}

	/**
	 * 异步删除商品（放入回收站）
	 */
	public function del(){

		//安全处理 
		if( !request()->isAjax() ){

			$this->error('您访问的页面不存在！');

		}

		$data['gid'] = input('id')+0;
		$data['is_delete'] = input('status')+0;

		if( db('goods')->strict(true)->update($data) ){

			echo true;

		}

	}

	/**
	 * 异步删除商品（真正删除）
	 */
	public function delGoods(){

		//安全处理 
		if( !request()->isAjax() ){

			$this->error('您访问的页面不存在！');

		}

		$gid = input('id')+0;

		if( db('goods')->delete($gid) ){

			echo true;

		}

	}

	/**
	 * 异步上传商品logo图
	 */
	public function uploadLogo(){

		// 设置这个脚本可以执行的时间，单位：秒，0：代表一直执行到结束，默认30秒
    	set_time_limit(0);

    	//上传图片
		if( $data = $this->uploadOne( 'Filedata', config('thumb.size') ) ){

			//删除原图
			@unlink( $data['pic'] );

			//将原图从数组中移除
			unset($data['pic']);

			//返回路径信息
			echo json_encode($data);

		}else{

			echo false;
			
		}


	}

	/**
	 * 异步删除图片
	 */
	public function delPics(){

		//安全处理 
		if( !request()->isAjax() ){

			$this->error('您访问的页面不存在！');

		}
		
		//获取信息
		$imgPath = input('path/a');
		$type = input('type','');
		
		foreach ($imgPath as $v) {
			
			//判断图片是否存在
			$v = '.'.$v;
			if( file_exists( $v ) ){

				unlink($v);
				
			}

		}

		//如果是修改商品，删除后要更新表字段
		if( $type =='edit' ) {

			$data['pic_small'] = '';
			$data['pic_medium'] = '';
			$data['pic_big'] = '';
			$data['gid'] = input('id')+0;

			db('goods')->strict(true)->update($data);

		}else if( $type =='pic' ) {

			db('pics')->delete( input('id')+0 );

		}

		echo true;

	}

	/**
	 * 异步修改相册排序
	 */
	public function changePicSort(){

		//安全处理 
		if( !request()->isAjax() ){

			$this->error('您访问的页面不存在！');

		}

		//收集数据
		$sort = input('num')+0;
		$id = input('id')+0;

		//更新排序
		db('pics')->strict(true)->where('pid','=',$id)->update( ['sort'=> $sort] );

	}

	/**
	 * 异步获取类型属性
	 */
	public function getTypeAttrs(){

		//安全处理 
		if( !request()->isAjax() ){

			$this->error('您访问的页面不存在！');

		}
		
		//获取信息
		$tid = input('id')+0;
		
		//获取该类型下的所有属性
		if( $attrs = db('attrs')->field( 'aid,attr_name,input_type,attr_value,attr_type' )->where( 'tid','=',$tid )->select() ){

			echo json_encode( ['status'=>true,'msg'=>$attrs] );

		}else{

			echo json_encode( ['status'=>false,'msg'=>'该类型下没有属性或者获取属性失败！'] );
		}

	}

	/**
	 * 展示货品
	 */
	public function product(){

		// 分配模版标头信息变量
		$this->setPageTitle( "货品列表","商品列表",url('lst') );

		// 获取该商品的规格与值
		$gid = input('id')+0;
		$field = 'a.aid,attr_name,ga.attr_value,ga.id';
		$data = db('goods_attrs as ga')->field( $field )->join('jd_attrs a','ga.aid = a.aid','LEFT')->where(['attr_type'=>1,'gid'=>$gid])->order('aid')->select();
		$attrs = [];
		foreach ($data as $k => $v) {
			
			if( isset( $attrs[$v['aid']] ) ) {

				$attrs[$v['aid']]['attr_value'][$v['id']] = $v['attr_value'];

			}else {

				$attrs[$v['aid']]['attr_name'] = $v['attr_name'];
				$attrs[$v['aid']]['attr_value'][$v['id']] = $v['attr_value'];
			}
		}
		//q($attrs);
		$count = count($attrs);
		// foreach ($attrs as $k => $v) {
		// 	$attrs[$k]['attr_value'] = explode(',', $v['attr_value']);
		// }

		// 获取该商品的所有货品及其属性值
		$data = db('product')->where('gid','=',$gid)->order('product_code')->select();

		// 获取该商品的所有属性值
		$info = db('goods_attrs as ga')->field('ga.*,a.attr_type')->join('jd_attrs a','ga.aid = a.aid','LEFT')->where( ['gid'=>$gid,'a.attr_type'=>1])->select();
		   
		// 拼凑货品数组
		$products = [];
		foreach ($data as $k => $v) {

			$v["attr_list"] = explode(',', $v["attr_list"]);

			foreach ($info as $k1 => $v1) {
				
				foreach ($v["attr_list"] as $k2 => $v2) {
						
					if( $v1['id'] == $v2 ){

						$v["attr_value"][$v1['id']] = $v1['attr_value'];

					}

				}

			}
			
			$products[ $v['pid'] ]['product_code'] = $v['product_code'];
			$products[ $v['pid'] ]['product_sku'] = $v['product_sku'];
			$products[ $v['pid'] ]['product_price'] = $v['product_price'];
			$products[ $v['pid'] ]['attr_value'] = $v['attr_value'];

		}
		
		
		//分配变量
		$this->assign('attrs',$attrs);
		$this->assign('count',$count);
		$this->assign('products',$products);
		
		return $this->fetch();

	}

	/**
	 * 添加货品
	 */
	public function addProduct(){
		
		// 安全处理 
		if( !request()->isPost() ){

			$this->error('您访问的页面不存在！');

		}

		// 处理数据
		$msg = input('post.product/a');
		$gid = input('post.goods_id')+0;
		$data = [];//用于拼接插入数据库的信息
		$productModel = db('product');
		$flag = false;//用于判断用户是否选择了属性
		$delFalg = true;//是否删除货品标志
		
		foreach ( $msg as $k => $v) {
			
			// 如果属性id不为空
			if( $v['attr_value'] = array_filter($v['attr_value']) ){

				// 证明用户选择了属性
				$flag = true;

				// 拼接插入数据库的信息
				$data['product_code'] = $v['goods_code'];
				$data['product_price'] = $v['goods_price'];
				$data['product_sku'] = $v['goods_number'];
				$data['attr_list'] =  implode(',', $v['attr_value']);
				$data['gid'] = $gid;

				// 获取属性值
				$attrVlaues = db('goods_attrs')->where('id','in',$data['attr_list'])->column('attr_value');
				$data['attr_value_list'] =  implode(',', $attrVlaues);

				//只删除一次
				if( $delFalg ){

					// 新增前先删除原有货品
					$productModel->where('gid','=',$data['gid'])->delete();

					$delFalg = false;

				}
				
				// 货号不能相同，如果数据库已经存在相同货号，就不处理
				if( !$productModel->where('product_code','=',$data['product_code'])->value( 'pid' ) ){

					// 添加货品
					$productModel->strict(true)->insert( $data );

				}
				
			}

		}
		
		if( $flag ){

			$this->success('添加成功',url('product',['id'=>$gid]));
		
		}else{

			$this->error('请选择规格组合！');

		}

	}

	/**
	 * 展示回收站商品
	 */
	public function recycle(){

		//分配模版标头信息变量
		$this->setPageTitle( "回收站列表","回收站列表",url('recycle') );

		//分页获取回收站商品信息
		$field = 'gid,goods_name,market_price,shop_price,is_promote,is_on_sale,is_hot,is_new,is_best,pic_small,sort,a.account';
		$goods = db('goods as g')->field($field)->join('jd_admin a','g.aid = a.aid','LEFT')->order('gid desc')->where('is_delete','=',1)->paginate(config('paginate.list_rows'));
			
		
		//分配变量
		$this->assign('goods',$goods);
		
		return $this->fetch();

	}


}